<?php

/**
 * 把访问记录从队列中添加到数据库
 * File Name：GuestController.php
 * File Encoding：UTF-8
 * File New Time：2014-8-12 14:04:35
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class GuestController extends YzwController {

    private $key = '_guest_add_stop_';

    public function actionIndex() {
        set_time_limit(600);
        header("Content-type: text/html; charset=utf-8");

        $stop = Yii::app()->cache->get($this->key);
        if (!empty($stop) && (int) $stop == 1) {
            echo "暂停数据写入";
            return true;
        }

        //删除旧记录
        $access_time = strtotime(date('Y-m-d 00:00:00')) - 86400 * 2;
        if ($access_time > 0) {
            GuestDataModel::model()->deleteAll(GuestDataModel::model()->where(array('access_time' => array('LT', $access_time), 'limit' => 10000)));
        }
        $xun = 0;
        $ok = 0;
        $err = 0;
        $kong = 0;
        $lun = 0;
        while ($lun <= 30 && $ok < 3000 && $kong < 3000) {
            for ($i = 0; $i < 200; $i++) {
                $xun ++;
                $data = RedisCluster::getInstance()->pop('guest_record');
                if (empty($data)) {
                    $kong++;
                    continue;
                }
                $model = new GuestDataModel();
                $model->attributes = $data;
                if ($model->save()) {
                    //来源分析结果
                    GuestRefererModel::model()->redisFenxi($model->attributes);
                    $ok ++;
                } else {
                    $err ++;
                }
            }
            $lun++;
            sleep(2);
        }
        echo "循环次数：{$xun}，成功：{$ok}，失败：{$err}，空数据：{$kong}";
    }

    public function actionStop() {
        header("Content-type: text/html; charset=utf-8");
        $time = (int) Yii::app()->request->getParam('time');
        Yii::app()->cache->set($this->key, 1, $time ? $time : 300);
        echo '已经暂停访客信息数据写入！';
    }

    public function actionDemo() {
        var_dump(RedisCluster::getInstance()->push('demo', array('demo')));
        var_dump(RedisCluster::getInstance()->pop('demo'));
        if ($_GET['act']) {
            print_r(RedisCluster::getInstance()->pop($_GET['act']));
        }
    }

}
